
#include <iostream>
#include <memory>
#include <string>
#include <unistd.h>
#include "TcpServer.hpp"
#include"HttpProtocol.hpp"
// 网络负责IO发送
// HandlerRequest字节流数据解析和调用业务处理方法的
// 处理报文的方法
// request: 我们认为我们已经读到了一个完整的请求了
std::string SuffixToType(const std::string &suffix)
{
    if (suffix == ".html" || suffix == ".html")
        return "text/html";
    else if (suffix == ".png")
        return "image/png";
    else if (suffix == ".jpg")
        return "image/jpeg";
    else
    {
        return "text/html";
    }
}
std::string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 301:
        return "Moved Permanently";
    case 307:
        return "Temporary Redirect";
    case 403:
        return "Forbidden";
    case 404:
        return "Not Found";
    case 500:
        return "Internal Server Error";
    default:
        return "Unknown";
    }
}

std::string HandlerHttpRequest(std::string &request)
{
    HttpRequest req;
     //反序列化
    req.Deserialize(request);
    req.Parse();
    req.DebugHttp();
    HttpResponse resp;
    std::string content;
    std::string path;
    int code=200;
      if(req.Url()=="/")
      {
         path=wwwroot+"/"+homepage;
        content=req.GetFileContentHelper(path);
      }
      else{
         path=wwwroot+req.Path();
        content=req.GetFileContentHelper(path);
      }
      if(content.empty())
      {
       code=404;
       resp.SetCode(code);
       resp.SetDesc(CodetoDesc(code));
       content=req.Get_404();
      }
        resp.MakeStatusLine();
        std::string content_len_str="Content-Length:"+to_string(content.size())+"\r\n";
        resp.AddHeader(content_len_str);
        std::string content_type_str="Content-Type:"+ SuffixToType(req.Suffix())+"\r\n";
        resp.AddHeader(content_type_str);
        std::string namecokie="Set-Cookie:username=zhangsan\r\n";
        resp.AddHeader(namecokie);
        std::string passwdcokkie="Set-Cookie:passwdcokkie=123456\r\n";
        resp.AddHeader(passwdcokkie);
        resp.AddContent(content);
        cout<<resp.Serialize();
        return resp.Serialize();

}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage : " << argv[0] << " port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> svr(new TcpServer(HandlerHttpRequest ,localport));

    svr->Loop();

    return 0;
}